import json
import urllib.request
import yaml

from flask import Flask, make_response, request

import redis

app = Flask(__name__)

app_id = ''
app_secret = ''
redis_host = ''
redis_port = 6379
auth_token = ''

# python3 -u /usr/etc/wechat_base.py >> /var/log/wechat_base.log 2>&1 &

# wx:
#   app_id: "wx123"
#   app_secret: "xxx"
# redis:
#   host: "localhost"
#   port: 6379
#  auth:
#    token: "123"
#


@app.route('/wx_access_token', methods=['GET'])
def get_token():
    param_token = request.args.get("token")
    if not param_token or param_token != auth_token:
        return make_response(str("illegal request!").encode('utf-8'), 401)

    access_token = redis.get('wx:ACCESS_TOKEN')  # 从redis中获取ACCESS_TOKEN
    if access_token:
        return access_token
    response_str = ''
    try:
        print("get access_token form wechat server.")
        token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(app_id, app_secret)  # 创建获取token的url
        response = urllib.request.urlopen(token_url)
        response_str = response.read().decode('utf-8')
        response_json = json.loads(response_str)
        access_token = response_json.get("access_token")
        print(access_token)
        redis.setex('wx:ACCESS_TOKEN', 7100, access_token)  # 将获取到的 ACCESS_TOKEN 存入redis中并且设置过期时间为7200s
        return make_response(access_token.encode('utf-8'), 200)
    except Exception as e:
        print(response_str)
        print(e)
        return make_response(str(response_str + str(e)).encode('utf-8'), 500)


@app.route('/check', methods=['GET'])
def check():

    return make_response(json.dumps('{}').encode('utf-8'), 200)


if __name__ == '__main__':
    with open("/opt/wx/config.yaml", "r") as file:
        wx_config = file.read()
        wx_config_yaml = yaml.safe_load(wx_config)
        app_id = wx_config_yaml['wx']['app_id']
        app_secret = wx_config_yaml['wx']['app_secret']
        if not app_id or not app_secret:
            print("Error: app_id or app_secret is not set.")
            exit(500)
        redis_host = wx_config_yaml['redis']['host']
        redis_port = wx_config_yaml['redis']['port']
        if not redis_host or not redis_port:
            print("Error: redis is not set.")
            exit(500)
        auth_token = wx_config_yaml['auth']['token']
    redis = redis.Redis(host=redis_host, port=redis_port)
    print("starting wechat_base.py")
    app.run(host='0.0.0.0', port=18000)
